import {getRequest} from "@/utils/requestUtil";
import api from "@/api";

export const formatRouters = (routers) => {
    let fmtRouters = [];
    routers.forEach(router => {
        let {path, component, name, iconCls, children} = router;
        //递归子路由
        if (children && children instanceof Array) {
            children = formatRouters(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            component:resolve=>{
                if (component.startsWith('Home')) {
                    require(['@/views/' + component + '.vue'], resolve);
                } else{
                    require(['@/views/'+component.substr(0,1).toLowerCase()+component.substr(1,2)+'/' + component + '.vue'],resolve)
                }
            }
        }
        fmtRouters.push(fmRouter)
    })
    return fmtRouters;
}

export const initMenu = (router, store) => {
    if (store.state.routers.length > 0) {
        return
    }
    getRequest(api.getMenuById).then(res => {
        if (res.data) {
            //格式化routers
            let fmtRouters = formatRouters(res.data);
            //添加到router
            router.addRoutes(fmtRouters);
            //将数据存入vuex
            store.commit("initRouters",fmtRouters)
            store.commit('initCurrentAdmin',JSON.parse(sessionStorage.getItem('user')))
            //发起websocket请求
            store.dispatch('connect')
        }
    }).catch(error=>{
        console.log("menuUtil错误信息："+error)
    })
}